﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Orange.Lib.Effective
{
    namespace QuerySyntaxUse
    {
        /// <summary>
        /// the same query result with diff implement.
        /// </summary>
        public class GetTuple
        {
            //命令式语法
            public IEnumerable<Tuple<int, int>> Method1()
            {
                var storage = new List<Tuple<int, int>>();
                for (int i = 0; i < 10; i++)
                {
                    for (int j = 0; j < 10; j++)
                    {
                        if (i + j < 10)
                        {
                            //yield return Tuple.Create(i, j);
                            storage.Add(Tuple.Create(i, j));
                        }
                    }
                }

                storage.Sort((x, y) =>
                         (x.Item1 * x.Item1 + x.Item2 + x.Item2)
                        .CompareTo(y.Item1 * y.Item1 + y.Item2 * y.Item2)
                );
                return storage;
            }

            //query syntax
            public IEnumerable<Tuple<int, int>> Method2()
            {
                return from x in Enumerable.Range(0, 10)
                       from y in Enumerable.Range(0, 10)
                       where x + y < 10
                       orderby x * x + y * y descending
                       select Tuple.Create(x, y);
            }

            //invoke method
            public IEnumerable<Tuple<int, int>> Method3()
            {
                return Enumerable.Range(0, 10)
                    .SelectMany(y => Enumerable.Range(0, 10), (x, y) => Tuple.Create(x, y))
                    .Where(p => p.Item1 + p.Item2 < 10)
                    .OrderByDescending(p => p.Item1 * p.Item1 + p.Item2 * p.Item2);
            }
        }
    }
}
